#coding=utf-8
from framework.db.mysql import BaseDb
from tornado import gen
from lib import log

class Canteen(BaseDb):

    @gen.coroutine
    def select_all_canteen(self, Fschool_id):
        sql = 'SELECT Fid, Fname, Fschool_id, Fcreate_time FROM tb_canteen WHERE Fschool_id = %s'

        ret = yield self.executejson(sql, (Fschool_id))
        raise gen.Return(ret)

    @gen.coroutine
    def select_canteen(self, school_id, page, offset):
        sql = '''SELECT Fid, Fname, Fschool_id, Fcreate_time
                FROM tb_canteen 
                WHERE Fschool_id = %s 
                LIMIT %s, %s'''
        count_sql = 'SELECT count(Fid) FROM tb_canteen a WHERE Fschool_id = %s'

        ret = yield self.executejson(sql, (school_id, page, offset))
        count = yield self.execute(count_sql, (school_id))

        raise gen.Return((ret, count[0][0]))

    @gen.coroutine
    def find_canteen(self, Fid):
        sql = '''SELECT Fid, Fname, Fschool_id, Fcreate_time
                FROM tb_canteen 
                WHERE Fid = %s '''

        ret = yield self.executejson(sql, (Fid))

        if len(ret) >= 1:
            raise gen.Return(ret[0])
        else:
            raise gen.Return({})

    @gen.coroutine
    def insert_canteen(self, canteen_info):

        ret = yield self.insert("tb_canteen", canteen_info)

        self.commit()

        raise gen.Return(ret)

    @gen.coroutine
    def del_canteen(self, Fid):
        sql = 'DELETE FROM tb_canteen WHERE Fid = %s'

        ret = yield self.upsert_commit(sql, (Fid))

        raise gen.Return(ret)

    @gen.coroutine
    def update_canteen(self, Fid, arg):
        canteen_sql = '''UPDATE tb_canteen SET %s WHERE Fid = %s'''

        update_data = ''
        for i in arg.keys():
            update_data += i + '=%s,'

        canteen_sql = canteen_sql % (update_data[0:-1], '%s')

        data = arg.values()
        data.append(Fid)

        ret = yield self.upsert(canteen_sql, tuple(data))

        self.commit()

        raise gen.Return(ret)